import util from './util';
import md5 from './md5';
import { APPID, APP_ENV, USER_VERSION} from './constant'
import { store } from '@/store/index'
function readUserSpecialInfo() {
  // 首次进入小程序, vuex会取不到值
  let user_special_info = store.state.userInfo;
  return user_special_info;
}

// 用于一般对外网接口请求
const wxRequest = async (params = {}, url) => {
  let user_special_info = readUserSpecialInfo();
  // let data = user_special_info || {};
  let data = params.query || {};
  data.appId = APPID;
  console.log('before assgin: %o', data);
  data.user_version = USER_VERSION;
  // 测试环境
  console.log('after assgin: %o', data);
  let requestRes = await uni.request({
    url: url,
    method: params.method || 'GET',
    data: data,
    // 小程序默认 对于 POST 方法且 header['content-type'] 为 application/json 的数据，进行 JSON 序列化;
    // 如此，导致服务器后台无法通过 request.getParameter()方法获取参数值。。故修改Content-Type
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'referrer': 'same-origin'
    },
  });
  if (requestRes.length && requestRes.length > 1) {
    let res = requestRes[1];
    if (res.statusCode == 404) {
      uni.showToast({
        title: 'request fail: 404', //提示的内容,
        icon: 'none', //图标,
        duration: 2000, //延迟时间,
      });
      return { data: { code: 0, status: 0, msg: `网络请求失败(request fail: 404)`, success: false } };
    } else {
      console.log('wxreqesut: %o',res);
      return res;
    }
  } else {
    let e = requestRes[0];
    uni.showToast({
      title: `网络请求失败(${e.errMsg || '加载失败'})`, //提示的内容,
      icon: 'none', //图标,
      duration: 2000, //延迟时间,
    });
    console.log(e);
    return { data: { code: 0, status: 0, msg: `网络请求失败(${e.errMsg || '加载失败'})`, success: false }};
  }
};

const wxRequestTwo = async (params = {}, url) => {
  uni.showLoading({
    mask: true
  })
  let res = await wxRequest(params, url);
  uni.hideLoading();
  return res;
}

const wxUploadFile = async (params = {}, url) => {
  let user_special_info = readUserSpecialInfo();
  let data = user_special_info || {};
  data.appId = APPID;
  data.sign = SIGN;
  data.time = TIMESTAMP;
  // data.user_version = user_special_info.user_version;
  data = {...data, ...params.query};
  let [error, res] = await uni.uploadFile({
    url: url, //开发者服务器 url
    filePath: params.filePath, //要上传文件资源的路径,
    formData: data,
    name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容,
    // header: {
    //   'Content-Type': 'multipart/form-data',
    // },
  });
  console.log('upload file res: %o', [error, res]);
  try {
    if (res) {
      res.data = JSON.parse(res.data);
      return res;
    } else {
      return { data: { code: 10000, msg: `文件上传失败${error.errMsg || ''}` }, success: false }
    }
  } catch (catchError) {
    return { data: { code: 10001, msg: `文件上传失败${catchError.message || ''}` }, success: false }
  }
};

module.exports = {
  wxRequest: wxRequest,
  wxRequestTwo: wxRequestTwo,
  wxUploadFile,
}
